<!--
 * @Author: Bonnie
 * @Date: 2021-12-03 15:32:23
 * @LastEditTime: 2021-12-20 16:47:00
 * @LastEditors: Bonnie
 * @Description: 上传文件
 * @FilePath: /public_demo/src/views/file/uploadFile.vue
-->

//  上传文件
<template>
  <div class="upload-container">
    这里是上传文件（可多选）
    <br />
    <em @click="toMDN" class="em-hover cursor-pointer underline">MDN链接</em>
    <br />
    <br />
    <div>
      原理：
      <br />1.利用input的type='file'属性
      <br />2.将input进行display隐藏
      <br />3.获取选择的文件
    </div>
    <div class="upload-div">
      <div class="btn" @click="upload">
        <p>点击上传</p>
      </div>
      <input type="file" ref="input_ref" multiple="multiple" @change="onChange" />
      <div class="select-file" v-if="nameList && nameList.length!=0">
        选择的文件：
        <br />
        <p v-for="(item,index) in nameList" :key="index">{{item.value}}</p>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  props: [],
  data() {
    return {
      nameList: []
    };
  },
  methods: {
    toMDN() {
      window.open(
        "https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/Input/file",
        "_blank"
      );
    },
    upload() {
      this.$refs.input_ref.click();
    },
    onChange(e) {
      const upList = Array.from(e.target.files) || [];
      let nameList = JSON.parse(JSON.stringify(this.nameList)) || [];
      if (upList && upList.length != 0) {
        upList.map((item, index) => {
          nameList.push({ key: name, value: item.name });
        });
      }
      this.nameList = JSON.parse(JSON.stringify(nameList));
    }
  }
};
</script>
<style lang='scss' scoped>
.upload-container {
  flex: 1;
  padding: 10px 20px;
  box-sizing: border-box;
  .upload-div {
    margin-top: 30px;
    .btn {
      cursor: pointer;
      height: 42px;
      text-align: center;
      border-radius: 12px;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 10px;
      font-size: 12px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      transition: all 0.2s ease;
      box-sizing: border-box;
      width: 110px;
      background-color: rgba(132, 63, 255, 1);
      color: #fff;
      &:hover {
        opacity: 0.8;
      }
    }
    input {
      display: none;
    }
  }
  .select-file {
    margin-top: 20px;

    p {
      padding-left: 20px;
    }
  }
}
</style>